const path = require('path')
const Router = require('koa-router')
const router = new Router
const utils = require('./utils')
const MySql = require('mysql2/promise')
const mysqldump = require('mysqldump')

//简单的自定义加密函数，让前端提交的密码看起来很屌的样纸
router.post('/token', async ctx => {
    return ctx.success(utils.parseCode(`function secret(pswd){
        pswd = window.btoa(pswd);
        var arr=[], len=pswd.length, f='*/^&$#@|!_',fl=f.length;
        for(var i=0; i<len; i++){
            arr.push(i);
        }
        arr.sort(function(){
            return Math.round(Math.random()*2 - 1);
        });
        arr.forEach(function(i, k){
            arr[k] = (k > 0 ? f.charAt(Math.floor(Math.random()*fl)) : '') + arr[k] + f.charAt(Math.floor(Math.random()*fl)) + pswd.charAt(i);
        });
        return arr.join('');
    } secret.toString = secret.prototype.toString = function(){return '(){***}'}`))
});

router.post('/conn', async ctx => {
    try{
        let {host, user, pswd} = ctx.data
        if(!host || !user || !pswd) return ctx.fail('缺少必要参数')
        let cookieCode = encodeURIComponent(host+' '+user+' '+pswd)
        let cfg = utils.parse([host, user, pswd])
        const conn = await MySql.createConnection({
            host: cfg[0],
            user: cfg[1],
            password: cfg[2]
        });
        conn.close()
        ctx.cookies.set(ctx.connid, cookieCode)
        return ctx.success()
    }catch(err){
        return ctx.fail(err.message)
    }
})

router.get('/dbhost', async ctx => {
    try{
        let cfg = utils.parse(ctx.cookies.get(ctx.connid))
        return ctx.success(cfg[0])
    }catch(err){
        return ctx.fail(err.message)
    }
})

router.post('/list', async ctx => {
    try{
        let list = []
        const mysql = await ctx.mysql()
        let [rows, fields] = await mysql.query('show databases')
        for(let row of rows){
            let dbname = row[fields[0].name]
            let item = {
                name: dbname,
                list: []
            }
            await mysql.query('use '+dbname)
            let [rows1, fields1] = await mysql.query('show tables')
            item.list = rows1.map(i => i[fields1[0].name])
            list.push(item)
        }
        mysql.end()
        return ctx.success(list)
    }catch(err){
        return ctx.fail(err.message)
    }
})

router.post('/table', async ctx => {
    try{
        let {database, table, start, num} = ctx.data
        start = +start || 0;
        num = +num || 25;
        if(!database || !table) return ctx.fail('缺少必要参数！')
        
        const mysql = await ctx.mysql()
        await mysql.query('use '+database)
        let [crow, cfield] = await mysql.query('select count(1) from '+table)
        let query = 'select * from '+table+' limit '+start+','+(start+num)
        let [rows, fields] = await mysql.query(query)
        mysql.end()
        return ctx.success({
            sql: query,
            start: start,
            num: num,
            total: crow[0][cfield[0].name],
            rows,
            fields: fields.map(item => {
                return {name: item.name}
            })
        })
    }catch(err){
        return ctx.fail(err.message)
    }
})

router.post('/export', async ctx => {
    try{
        let mysql = await ctx.mysql()
        let {host, port, user, password} = mysql.connection.config
        let {database, tables} = ctx.data
        if(!database) return ctx.fail('database为必传参数')
        if(tables && !Array.isArray(tables)) return ctx.fail('tables必须为数组')
        const options = {
            connection: {
                host,
                port,
                user,
                password,
                database,
            },
            dumpToFile: path.resolve(__dirname, '../client/download/'+database+'.sql')
        }
        if(tables){
            options.dump =  {tables}
        }
        await mysqldump(options);
        return ctx.success({
            download: './download/'+database+'.sql'
        })
    }catch(err){
        return ctx.fail(err.message)
    }
})

router.post('/import', async ctx => {
    try{
        let {sql, database} = ctx.data
        console.log(sql)
        return ctx.success({})
    }catch(err){
        return ctx.fail(err.message)
    }
})

module.exports = router